package edu.utn.tacs.grupouno.ui.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;

import edu.utn.tacs.grupouno.ui.client.dto.TurnoSemanalDTO;

public class TurnoSemanalCreationPanel extends VerticalPanel {
	
	private DialogBox dialogBox;

	public TurnoSemanalCreationPanel() {
		initComponents();
	}

	public TurnoSemanalCreationPanel(DialogBox box) {
		this.dialogBox = box;
		initComponents();
	}

	private void initComponents() {
		final DateBox dateBox = new DateBox();
		dateBox.setFormat(new DateBox.DefaultFormat(DateUtil.getFormat()));
		
		Panel datePanel = new HorizontalPanel();
		datePanel.add(new Label("Vigente desde: "));
		datePanel.add(dateBox);
		
		Panel horarioPanel = new HorizontalPanel();
		horarioPanel.add(new Label("Horario: "));
		
		final ListBox horarios = new ListBox(false);
		for(int i = 8; i < 18; i++) {
			horarios.addItem(i + ":00");
			horarios.addItem(i + ":30");
		}
		horarioPanel.add(horarios);
		
		Panel diaPanel = new HorizontalPanel();
		diaPanel.add(new Label("Dia de la semana: "));
		
		final ListBox dias = new ListBox(false);
		for(String dia : new String[]{"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"}) {
			dias.addItem(dia);
		}
		diaPanel.add(dias);
		
		final HorizontalPanel errorPanel = new HorizontalPanel();
		
		final Button save = new Button("Agregar");
		save.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent arg0) {
				TurnoSemanalDTO dto = new TurnoSemanalDTO();
				dto.setFechaInicio(dateBox.getValue());
				dto.setHorario(horarios.getItemText(horarios.getSelectedIndex()));
				dto.setDiaDeLaSemana(dias.getItemText(dias.getSelectedIndex()));
				
				final TurnoUIServiceAsync turnoService = GWT.create(TurnoUIService.class);
				turnoService.addTurnoSemanal(dto, new AsyncCallback() {
					@Override
					public void onFailure(Throwable arg0) {
						Label error = new Label("Error al guardar. Intente nuevamente");
						error.setStyleName("error");
						errorPanel.add(error);
						save.setText("Agregar");
						save.setEnabled(true);
					}
					@Override
					public void onSuccess(Object arg0) {
						if(dialogBox != null) {
							dialogBox.hide();
						}
					}
				});
				errorPanel.clear();
				save.setText("Guardando...");
				save.setEnabled(false);
			}
		});
		
		setSpacing(4);
		add(datePanel);
		add(horarioPanel);
		add(diaPanel);
		add(save);
		add(errorPanel);
	}

}
